import { login, logout, getInfo } from '@/api/user'
import { getToken, setUser, removeUser } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
	return {
		token: getToken(),
		userId: 0,
		roleId: 0,
		authority: 0
	}
}

const state = getDefaultState()

const mutations = {
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState())
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USER_ID: (state, userId) => {
		state.userId = userId
	},
	SET_ROLE: (state, [roleId, authority]) => {
		state.roleId = roleId
		state.authority = authority
	}
}

const actions = {
	// user login
	login({ commit }, userInfo) {
		const { account, password } = userInfo
		return new Promise((resolve, reject) => {
			login({ userId: account.trim(), userPassword: password }).then(response => {
				const { data } = response
				commit('SET_TOKEN', data.token)
				// commit('SET_USER_ID', data.userId)
				// commit('SET_ROLE', data.roleId, data.authority)
				setUser(data)
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// get user info
	getInfo({ commit, state }) {
		return new Promise((resolve, reject) => {
			getInfo(state.token).then(response => {
				const data = response.data

				if (!data) {
					return reject('用户信息获取失败')
				}
				// console.log(data)
				commit('SET_USER_ID', data.userId)
				commit('SET_ROLE', [data.roleId, data.authority])
				setUser(data)
				resolve(data)
			}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	logout({ commit, state }) {
		return new Promise((resolve, reject) => {
			logout(state.token).then(() => {
				removeUser() // must remove  token  first
				resetRouter()
				commit('RESET_STATE')
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// remove token
	resetUser({ commit }) {
		return new Promise(resolve => {
			removeUser() // must remove  token  first
			commit('RESET_STATE')
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}

